from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView
from .ser import *
from .models import *


class UserView(APIView):
    def post(self,request):
        name = request.data.get('name')
        password = request.data.get('password')

        # 反序列化
        user = User.objects.filter(name=name).first()

        # 判断用户是否存在
        if user:
            # 判断密码是否正确
            if user.password ==password:
                return Response({'msg':'登录成功'})
            else:
                return Response({'msg':'登陆失败'})

        else:
            return Response({'msg':'登录失败'})

    def get(self,request):
        user_li = User.objects.all().values()
        return Response(user_li)

class FictionView(APIView):
    def post(self,request):
        fiction_ser = FictionSer(data=request.data)
        fiction_ser.is_valid(raise_exception=True)
        fiction_ser.save()
        return Response({'msg':'添加小说成功','code':200})

    def get(self,request):
        fiction_li = Fiction.objects.all().values()
        return Response(fiction_li)

    def delete(self,request):
        id = request.GET.get('id')
        Fiction.objects.filter(id=id).delete()
        return Response({'msg':'删除小说成功'})



class FyView(APIView):
    def get(self,request):
        page  = int(request.GET.get('page',1))
        size = 2

        start = (page-1)*size
        end = page*size

        fiction_li = Fiction.objects.order_by()[start:end]
        total = Fiction.objects.all().count()
        fiction_li_ser = FictionSer(fiction_li,many=True)
        return Response({'msg':'查询成功','code':200,'fiction_li':fiction_li_ser.data,'total':total})




class DetailsView(APIView):
    def get(self,request):
        id = request.GET.get('id')

        fiction_li = Fiction.objects.filter(id=id).first()

        fiction_li1 = {
            'id' : fiction_li.id,
            'name' : fiction_li.name,
            'user' : fiction_li.user.name,
            'details' : fiction_li.details,
            'img': fiction_li.img.name,
            'create_time' : fiction_li.create_time

        }
